import cv2
import mediapipe as mp

# 初始化MediaPipe手势模块
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(static_image_mode=False, max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5)

# 捕获视频帧
cap = cv2.VideoCapture(0)

while True:
    # 从摄像头读取一帧图像
    ret, frame = cap.read()
    if not ret:
        break

    # 水平翻转图像，以便正像显示q
    frame = cv2.flip(frame, 1)
    # 将图像从BGR转换为RGB，因为MediaPipe需要RGB图像
    image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # 进行手势检测
    results = hands.process(image)

    # 如果检测到手势
    if results.multi_hand_landmarks:
        for hand_landmarks in results.multi_hand_landmarks:
            # 遍历每个手势关键点，并在图像上绘制
            for landmark in hand_landmarks.landmark:
                cv2.circle(frame, (int(landmark.x * frame.shape[1]), int(landmark.y * frame.shape[0])), 5, (255, 0, 0), cv2.FILLED)

            # 绘制手势关键点的连线
            for i, landmark in enumerate(hand_landmarks.landmark):
                if i < 4:  # 仅绘制手指的前4个关键点
                    continue
                cv2.line(frame, (int(landmark.x * frame.shape[1]), int(landmark.y * frame.shape[0])),
                        (int(hand_landmarks.landmark[i - 1].x * frame.shape[1]), int(hand_landmarks.landmark[i - 1].y * frame.shape[0])),
                        (255, 0, 0), 2)

    # 显示带有手势标记的图像
    cv2.imshow('Hand Gesture Detection', frame)

    # 按'q'键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源
cap.release()
cv2.destroyAllWindows()